<template>
  <div ref="mapRef" class="com-full" style="background: #c4c4c4"></div>
</template>

<script setup>
import { ref, onMounted, shallowRef, watch } from "vue";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-rotatedmarker";
import airplaneImg from "@/assets/airplane-green.png";
import Icon2 from "@/assets/icon.png";
import "./AnimatedMarker";

const props = defineProps({
  pointList: {
    type: Array,
    default: () => [],
  },
  targetPoint: {
    type: Array,
    default: () => [],
  },
});

const mapRef = ref();
const map = shallowRef();
const pointLayer = shallowRef();

const initMap = () => {
  map.value = L.map(mapRef.value, {
    attributionControl: false,
    minZoom: 3,
    maxZoom: 10,
    // crs: L.CRS.EPSG3857,
    // center: [113.81841, 22.637524],
    // zoom: 13,
  }).setView([22.637524, 113.81841], 5);

  // 底图瓦片
  const baseLayer = L.tileLayer(import.meta.env.VITE_MAP_SATELLITE_URL);
  // 省市瓦片
  const overLayer = L.tileLayer(import.meta.env.VITE_MAP_OVERLAY_URL);

  baseLayer.addTo(map.value);
  overLayer.addTo(map.value);
};

const addPoint = () => {
  if (pointLayer.value) pointLayer.value.remove();
  if (props.pointList.length === 0) return;

  pointLayer.value = L.layerGroup().addTo(map.value);

  const latlngs = props.pointList.map((item) => [item.la, item.lo]);
  const lastPoint = latlngs[latlngs.length - 1];
  L.tooltip(lastPoint, {
    content: `
      <div style='
        border-radius: 4px;
        width: 100%;
        height: 100%;
        background-color: rgba(34, 149, 215, 0.8);
        padding: 5px'
      >
        ${props.pointList[0]?.flightId}
        <br>
        ${props.pointList[0]?.ft}
      </div>
    `,
    permanent: true,
  }).addTo(pointLayer.value);

  // 飞行轨迹
  let polyline = L.polyline(latlngs, { color: "#c4fd08" }).addTo(pointLayer.value);
  let icon = L.icon({
    iconUrl: airplaneImg,
    iconSize: [30, 30],
    iconAnchor: [15, 15],
  });

  let icon2 = L.icon({
    iconUrl: Icon2,
    iconSize: [20, 20],
    iconAnchor: [10, 20],
  });

  L.marker(latlngs[0], {
    icon: icon2,
  }).addTo(pointLayer.value);

  // 动态marker
  const list = polyline.getLatLngs().slice(latlngs.length - 50);
  let animatedMarker = L.animatedMarker(list, {
    speedList: latlngs.map(() => 500),
    interval: 100,
    icon: icon,
  }).addTo(pointLayer.value);
  animatedMarker.start();

  if (props.targetPoint.length) {
    L.marker(props.targetPoint, {
      icon: icon2,
    }).addTo(pointLayer.value);
    // 计划飞行
    L.polyline([lastPoint, props.targetPoint], { color: "#c4fd08", dashArray: "12" }).addTo(
      pointLayer.value
    );
  }
};

onMounted(() => {
  initMap();
  watch(
    () => props.pointList,
    (v) => {
      if (v.length) {
        addPoint();
      }
    }
  );
});

defineExpose({});
</script>

<style scoped lang="scss">
:deep(.leaflet-tooltip) {
  background-color: transparent;
  border: 0;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0);
  color: #fff;
}
</style>
